package com.control.back.halo.manage.controller;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.crypto.hash.Sha256Hash;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

@RequestMapping("/login")
@Controller
public class LoginController {
    
    @RequestMapping({ "", "index" })
    public String loginView() {
        return "/authorization/login";
    }

    @RequestMapping(value = "/submit", method = RequestMethod.POST)
    public String submit(String username, String password) {
        try {
            Subject subject = SecurityUtils.getSubject();
            // sha256加密
            password = new Sha256Hash(password).toHex();
            UsernamePasswordToken token = new UsernamePasswordToken(username, password);
            subject.login(token);
        } catch (UnknownAccountException e) {
            return "redirect:index.html";
        } catch (IncorrectCredentialsException e) {
            return "redirect:index.html";
        } catch (LockedAccountException e) {
            return "redirect:index.html";
        } catch (AuthenticationException e) {
            return "redirect:index.html";
        }

        return "redirect:/index.html";
    }
}
